﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWMAG.Scripting.AST.ObjectModel;
using IWMAG.Scripting.Types;
using IWMAG.Scripting.Compiler;
using IWMAG.Scripting.Interpreter;

namespace IWMAG.Scripting.AST.Operators {
    internal class CastOperator : CodeExpression {
        public CodeType Type;
        public CodeExpression Expression;
        private CodeType ExpressionType;

        public CastOperator(Lexeme l, CodeType type, CodeExpression expr) : base(l) {
            Type = type;
            Expression = expr;
        }

        public override void Verify(Scripting.Helpers.CompileTable sym, List<IUserInfo> error) {
            Expression.Verify(sym, error);

            ExpressionType = Expression.TypeOf();
        }

        public override CodeType TypeOf() {
            return Type;
        }

        public override IEnumerable<Continuation> ValueOf(Interpreter.ScriptEngine engine, Scripting.Helpers.RuntimeTable sym, Interpreter.Reference<Interpreter.RunValue> val) {
            foreach (Continuation wait in Expression.ValueOf(engine, sym, val)) yield return wait;
            Type totype = Marshaller.Marshal(Type, engine.CompiledTable);

            engine.IsExterned = true;
            val.ReferencedValue.Value = Marshaller.Cast(val.ReferencedValue.Value, ExpressionType, totype);
            engine.IsExterned = false;
        }
    }
}
